//
//  THCpcTaskPublishVC.m
//  YJB
//
//  Created by YJB on 2016/11/28.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "THCpcTaskPublishVC.h"
#import "YJGlobalHeader.h"
#import "masonry.h"
#import "THTaskProtocolVC.h"
#import "YJUserDefaultTool.h"
#import "YJNetworkTool.h"

@interface THCpcTaskPublishVC ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *adsTitle;
@property (weak, nonatomic) IBOutlet UITextField *url;
@property (weak, nonatomic) IBOutlet UITextField *total;
@property (weak, nonatomic) IBOutlet UITextField *price;
@property (weak, nonatomic) IBOutlet UITextField *requirGlod;
@property (weak, nonatomic) IBOutlet UITextField *stopTime;
@property (weak, nonatomic) IBOutlet UIButton *publishBtn;
@property (weak, nonatomic) IBOutlet UIView *containView;

@property(nonatomic,strong)UIView  *popView;
@property(nonatomic,weak)UIButton *selectTimeBtn;
@property (weak, nonatomic) IBOutlet UIButton *checkProtocolBtn;

@end

@implementation THCpcTaskPublishVC
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"发布任务";
    self.checkProtocolBtn.selected = YES;
    NSArray *textFields = @[_adsTitle,_url,_total,_price,_requirGlod,_stopTime];
    self.publishBtn.enabled = YES;
    for (int i = 0; i < textFields.count; i ++)
    {
        UIView *leftView = [[UIView alloc]init];
        leftView.width = 12;
        UITextField *textField = textFields[i];
        textField.leftView = leftView;
        textField.leftViewMode = UITextFieldViewModeAlways;
    }
    
    //rac部分
    RAC(self.requirGlod,text) = [[RACSignal combineLatest:@[_price.rac_textSignal,_total.rac_textSignal] reduce:^id(NSString *price,NSString *total){
        return [@(price.doubleValue * total.doubleValue) stringValue ];
    }] skip:1];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
    @weakify(self);
    [tap.rac_gestureSignal subscribeNext:^(id x) {
        @strongify(self);
        [self.view endEditing:YES];
        self.popView.hidden = YES;
    }];
    [_containView addGestureRecognizer:tap];
    //发布按钮触发事件
    [[_publishBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        NSArray *messages = @[@"请输入任务标题",@"请输入任务地址",@"请输入任务总量",@"请输入单价"];
        NSArray *textFields = @[self.adsTitle,self.url,self.total,self.price];
        for (int i = 0; i < messages.count ; i ++)
        {
            UITextField *textField = textFields[i];
            if (textField.text.length == 0)
            {
                [MBProgressHUD showError:messages[i]];
                return;
            }
            if (i == 1 && ![textField.text isUrlString])
            {
                [MBProgressHUD showError:@"任务地址格式不对"];
                return;
            }
        }

        [self publishTask];
    }];
}

- (void)publishTask{
    
    [MBProgressHUD showMessage:@""];
    NSString *strTest = [[@"admin"stringByAppendingString:@"iOS"]stringByAppendingString:appMd5Key];
    NSString *keyStr = [strTest md5];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"action"] = @"set_cpcclick_add";
    params[@"makegold"] = @{@"username":[YJUserDefaultTool readUserName],
                            @"adv_title":_adsTitle.text,
                            @"adv_url":_url.text,
                            @"adv_icon":@"http://www.baidu.com",
                            @"total_num":_total.text,
                            @"gold_one":_price.text,
                            @"operate_need":@"图文混排信息",
                            @"method":@"2",
                            @"ans_match1":@"2",
                            @"ans_result1":@"CPC",
                            @"ans_request1":@"任务",
                            @"user_info":@"admin",
                            @"phone_info":@"iOS",
                            @"md5_key":keyStr,
                            };
    
    [YJNetworkTool postWithUrl:THURL(@"cpcclick.php") parameters:params success:^(id responseObject) {
        [MBProgressHUD hideHUD];
        if ([responseObject[@"return"][@"code"] integerValue] == 200)
        {
            [MBProgressHUD showSuccess:@"发布成功"];
        }else
        {
            NSString *message = responseObject[@"return"][@"message"];
            [MBProgressHUD showError:message toView:self.view];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络不佳,稍后重试" toView:self.view];
    }];
}

//- (void)publishTask
//{
//    NSString *stopTime = [self.stopTime.text substringToIndex:self.stopTime.text.length - 1];
//    [MBProgressHUD showMessage:@""];
//    NSString *strTest = [[@"admin"stringByAppendingString:@"iOS"]stringByAppendingString:Md5Key];
//    NSString *keyStr = [strTest md5];
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    params[@"action"] = @"set_cpcclick_add";
//    //        params[@"makegold"] = @{@"username":[YJUserDefaultTool readUserName],
//    //                                @"sitename":self.adsTitle.text,
//    //                                @"url":self.url.text,
//    //                                @"surflimit":_total.text,
//    //                                @"uprice":_price.text,
//    //                                @"stop_sec":stopTime,
//    //                                @"user_info":@"admin",
//    //                                @"phone_info":@"iOS",
//    //                                @"md5_key":keyStr,
//    //                                };
//    params[@"makegold"] = @{@"username":[YJUserDefaultTool readUserName],
//                            @"adv_title":self.adsTitle.text,
//                            @"adv_url":self.url.text,
//                            @"adv_icon":@"",
//                            @"total_num":_total.text,
//                            @"gold_one":_price.text,
//                            @"stop_sec":stopTime,
//                            @"user_info":@"admin",
//                            @"phone_info":@"iOS",
//                            @"md5_key":keyStr,
//                            };
//    
//    [YJNetworkTool postWithUrl:THURL(@"cpcclick.php ") parameters:params success:^(id responseObject) {
//        [MBProgressHUD hideHUD];
//        if ([responseObject[@"return"][@"code"] integerValue] == 200)
//        {
//            [MBProgressHUD showSuccess:@"发布成功"];
//            [NOTIFICATIONCENTER postNotificationName:THUserDidPublishCpcTaskNotification object:nil userInfo:nil];
//            [self.navigationController popViewControllerAnimated:YES];
//        }else
//        {
//            NSString *message = responseObject[@"return"][@"message"];
//            [MBProgressHUD showError:message toView:self.view];
//        }
//    } failure:^(NSError *error) {
//        [MBProgressHUD hideHUD];
//        [MBProgressHUD showError:@"网络不佳,稍后重试" toView:self.view];
//    }];
//}

- (IBAction)choiceTime:(UIButton *)button
{
    self.popView.hidden = !self.popView.hidden;
}

- (IBAction)cancelBtnClick:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)protocolBtnClick:(UIButton *)button
{
    [self.navigationController pushViewController:[THTaskProtocolVC new] animated:YES];
}

- (IBAction)checkProtocolBtnClick:(UIButton *)button
{
    button.selected = !button.selected;
    self.publishBtn.enabled = button.selected;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
    self.popView.hidden = YES;
}

-(UIView *)popView
{
    if (_popView == nil)
    {
        _popView = [[UIView alloc]init];
        _popView.backgroundColor = kUIColorFromRGB(0x999999);
        _popView.hidden = YES;
        _popView.height = 226;
        _popView.width = 100;
        [_containView addSubview:_popView];
        [_popView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(226);
            make.width.mas_equalTo(100);
            make.left.mas_equalTo(_stopTime.mas_left).offset(1);
            make.top.mas_equalTo(_stopTime.mas_bottom);
        }];
        
        NSMutableArray *buttons = [NSMutableArray array];
        NSArray *titles = @[@"10秒",@"15秒",@"20秒",@"25秒",@"30秒"];
        YJWeakSelf
        for (int i = 0; i < titles.count; i ++)
        {
            UIButton *btn = [[UIButton alloc]init];
            btn.titleLabel.font = FONT(14);
            btn.adjustsImageWhenHighlighted = YES;
            [btn setTitle:titles[i] forState:UIControlStateNormal];
            [btn setTitleColor:kUIColorFromRGB(0x666666) forState:UIControlStateNormal];
            [btn setTitleColor:WHITECOLOR forState:UIControlStateSelected];
            [btn setBackgroundImage:Image(@"cpc_timeChoice") forState:UIControlStateNormal];
            [btn setBackgroundImage:Image(@"cpc_timeChoice_select") forState:UIControlStateSelected];
            
            [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton *button) {
                weakSelf.selectTimeBtn.selected = NO;
                button.selected = YES;
                weakSelf.selectTimeBtn = button;
                weakSelf.stopTime.text = button.titleLabel.text;
                weakSelf.popView.hidden = YES;
            }];
            [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -40, 0, 0)];
            [_popView addSubview:btn];
            [buttons addObject:btn];
            if (i == 2)
            {
                btn.selected = YES;
                self.selectTimeBtn = btn;
            }
        }
        [buttons mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0.5);
            make.right.mas_equalTo(-0.5);
        }];
        [buttons mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedSpacing:0.5 leadSpacing:0.5 tailSpacing:0.5];
    }
    return _popView;
}


@end
